package com.wqiuqiu.gulimall.cart.interceptor;


import com.wqiuqiu.common.constant.CookieConstant;
import com.wqiuqiu.common.constant.RedisConstant;
import com.wqiuqiu.common.to.login.MemberResponseTo;
import com.wqiuqiu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();


    /**
     * 执行方法之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberResponseTo member = (MemberResponseTo)session.getAttribute(RedisConstant.SESSIONNAME);
        if (member != null){
            Long id = member.getId();
            userInfoTo.setUserId(id);
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CookieConstant.TEMP_USER_COOKIE_NAME)){
                    //得到cookie里面的值 uer-key
                    String uer_key = cookie.getValue();
                    userInfoTo.setUserKey(uer_key);
                    userInfoTo.setTemp(true);
                }
            }
        }
        //没登陆，也没有临时的user-key
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            userInfoTo.setUserKey(UUID.randomUUID().toString());
        }
        //给线程缓存加入UserInfoTo
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 方法执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //将添加的临时user-key发送给浏览器
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTemp()){
            Cookie cookie = new Cookie(CookieConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain(CookieConstant.DOMAIN);
            cookie.setMaxAge(CookieConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
